package cskevin.thermometer.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.samples.Item;
import net.simonvt.menudrawer.samples.MenuAdapter;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewSeriesStyle;
import com.jjoe64.graphview.LineGraphView;

import cskevin.thermometer.R;
import cskevin.thermometer.bean.WeatherBean;
import cskevin.thermometer.dao.biz.NetAtmosphereManager;
import cskevin.thermometer.utils.MyApplication;
import cskevin.utils.ScreenshotsUtils;
import cskevin.utils.ShareUtils;


/**
 * 菜单界面
 * @author csKevin
 *
 */
public class MenuActivity extends Activity implements PullToRefreshAttacher.OnRefreshListener{
	
	private static final int TEMPERATURE_RANGE = 50;
	private static final String TEMPERATURE_CHANGE_CURVE = "温度变化曲线图(时/x,摄氏度℃/y)";
	private static final String CURRENT_TIME_TEMPERATURE = "实时测控温度";
	private static final String WB_TEMPERETURE = "气象局发布温度";
	 
	private MenuDrawer mDrawer;
	private MenuAdapter mAdapter;
	private ListView mList;
	protected Context context;
	private View content;
	private LayoutInflater inflater;
	private ActionBar ab;
	private Resources res;
	protected PullToRefreshAttacher mPullToRefreshAttacher;
	protected NetAtmosphereManager manager;
	protected WeatherBean wb;
	private MyApplication myApplication;
		@Override
	    protected void onCreate(Bundle inState) {
	        super.onCreate(inState);
	        initData();
	        initFace();
	        
	        /* *******************************************************************
	         * 侧滑菜单选择监听
	         * *******************************************************************
	         */
	        mList.setOnItemClickListener(new OnItemClickListener() {

				@SuppressLint("NewApi")
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					switch (arg2) {
					case 0://首页
						mDrawer.toggleMenu();
						ab.setTitle(res.getString(cskevin.thermometer.R.string.app_name));
						configHomePage();
						break;
					case 1://设置
						mDrawer.toggleMenu();
						ab.setTitle(res.getString(cskevin.thermometer.R.string.menu_settings));
						break;
					case 2://关于
						mDrawer.toggleMenu();
						ab.setTitle(res.getString(cskevin.thermometer.R.string.about));
						content = inflater.inflate(cskevin.thermometer.R.layout.act_about, null);
						break;
					default:
						break;
					}
					mDrawer.setContentView(content);
				}
			});
	    }
		
		/**
		 ***********************************************************************************
		 * 配置下拉刷新
		 ***********************************************************************************
		 */
		private void configPullToRefresh() {
			// Retrieve the PullToRefreshLayout from the content view
			PullToRefreshLayout ptrLayout = (PullToRefreshLayout)content.findViewById(cskevin.thermometer.R.id.ptr_layout);

			// Give the PullToRefreshAttacher to the PullToRefreshLayout, along with the refresh
			// listener (this).
			ptrLayout.setPullToRefreshAttacher(mPullToRefreshAttacher, MenuActivity.this);
		}
	    /**
	     ***********************************************************************************
	     * 初始化一些数据
	     ***********************************************************************************
	     */
		@SuppressLint("NewApi")
		private void initData() {
			context = this;
			myApplication = (MyApplication)getApplicationContext();
	        inflater = LayoutInflater.from(context);
	        ab = getActionBar();
	        res = getResources();
			mPullToRefreshAttacher = PullToRefreshAttacher.get(MenuActivity.this);
		}
	    /**
	     ***********************************************************************************
	     * 初始化界面
	     * 1。设置侧滑菜单
	     * 2。设置首页显示
	     ***********************************************************************************
	     */
		@SuppressLint({ "NewApi", "ResourceAsColor" })
		private void initFace() {
			Drawable drawable = res.getDrawable(cskevin.thermometer.R.color.action_bar);
			ab.setBackgroundDrawable(drawable);
			configHomePage();
	        //菜单初始化
			mDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
	        List<Object> items = new ArrayList<Object>();
	        items.add(new Item(res.getString(cskevin.thermometer.R.string.home) ,cskevin.thermometer.R.drawable.home));
	        items.add(new Item(res.getString(cskevin.thermometer.R.string.menu_settings), cskevin.thermometer.R.drawable.setting));
	        items.add(new Item(res.getString(cskevin.thermometer.R.string.about), cskevin.thermometer.R.drawable.about));
	        mList = new ListView(this);
	        mAdapter = new MenuAdapter(this, items);
	        mList.setAdapter(mAdapter);
	        mDrawer.setMenuView(mList);
	        mDrawer.setContentView(content);
		    mDrawer.setSlideDrawable(R.drawable.ic_drawer);
		    mDrawer.setDrawerIndicatorEnabled(true);
		}

		/**
		 * ****************************************************************************************
		 * 配置首页
		 * ****************************************************************************************
		 */
		private void configHomePage() {
			if(myApplication.getvHome() != null){
				content = myApplication.getvHome();
			}else{
				content = inflater.inflate(cskevin.thermometer.R.layout.activity_main, null);
				configPullToRefresh();
			}
			new WeatherTask().execute();
	        mPullToRefreshAttacher.setRefreshing(true);
		}
		/**
		 ***********************************************************************************
		 *  设置曲线数据
		 * @param content
		 ***********************************************************************************
		 */
		private void setGraphData() {
			
			//配置网络数据
			TextView tv_netTemp = (TextView)content.findViewById(R.id.tv_issue_thermometer);
			TextView tv_netTime = (TextView)content.findViewById(R.id.tv_issue_time);
			tv_netTemp.setText(wb.getTemperature() + res.getString(R.string.she_shi_du));
			tv_netTime.setText(wb.getIssueTime()+"发布");
			// random curve
			int num = 24;
			/*
			 * 气象局发布数据
			 */
			GraphViewData[] data = new GraphViewData[num];
			for (int j = 0, i=0; i<num; i++ ,j+=10) {
				data[i] = new GraphViewData(j, Math.random()*TEMPERATURE_RANGE);
			}
			GraphViewSeries seriesIssue = new GraphViewSeries(WB_TEMPERETURE, new GraphViewSeriesStyle(Color.rgb(63, 180, 56), 3), data);
			/*
			 * 实时测量数据
			 */
			data = new GraphViewData[num];
			for (int j = 0,i=0; i<num; i++,j+=10) {
				data[i] = new GraphViewData(j, Math.random()*TEMPERATURE_RANGE);
			}
			GraphViewSeries seriesMonitor = new GraphViewSeries(CURRENT_TIME_TEMPERATURE, new GraphViewSeriesStyle(Color.rgb(60, 130, 197), 3), data);
			// graph with dynamically genereated horizontal and vertical labels
			LineGraphView graphView = new LineGraphView(context ,TEMPERATURE_CHANGE_CURVE);
			//配置表格
			String[] time = {"00:00","03:00","06:00","09:00","12:00","15:00","18:00","21:00"};
			String[] temp = {"50","40","30","20","10","0","-10","-20","-30","-40","-50"};
			graphView.setHorizontalLabels(time);
			graphView.setVerticalLabels(temp);
			graphView.addSeries(seriesIssue);
			graphView.addSeries(seriesMonitor);
			// set legend
			graphView.setShowLegend(true);
			graphView.setScrollable(true);
			LinearLayout ll_graph = (LinearLayout)content.findViewById(cskevin.thermometer.R.id.ll_graph);
			ll_graph.addView(graphView);
		}
		/**
		 * ***********************************************************************************
		 * 
		 * ***********************************************************************************
		 */
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	            case android.R.id.home:
	                mDrawer.toggleMenu();
	                break;
	            case cskevin.thermometer.R.id.action_location://位置服务
	            	/*
	            	 * 测试数据
	            	 */
	            	if(item.getTitle().equals("成都")){
	            		item.setTitle("重庆");
	            	}else{
	            		item.setTitle("成都");
	            	}
	            	break;
	            case cskevin.thermometer.R.id.action_share://分享
	            	share();
	            	break;
	        }

	        return super.onOptionsItemSelected(item);
	    }
	    
	    /**
	     ***********************************************************************************
	     * 分享
	     ***********************************************************************************
	     */
		private void share() {
			String uriStr = ScreenshotsUtils.screenshots1(getWindow().getDecorView());
			Uri uri = Uri.fromFile(new File(uriStr));
			ShareUtils.share(context, "我正在使用CS温度计，轻松掌控身边温度！http://www.guigulab.org", uri);
		}
	    /**
	     ***********************************************************************************
	     * 菜单(non-Javadoc)
	     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	     ***********************************************************************************
	     */
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu items for use in the action bar
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(cskevin.thermometer.R.menu.main, menu);
	        return super.onCreateOptionsMenu(menu);
	    }
	    /**
	     ***********************************************************************************
	     * 刷新监听
	     ***********************************************************************************
	     */
		@Override
		public void onRefreshStarted(View view) {
			// TODO Auto-generated method stub
	        new WeatherTask().execute();
		}
		
		/**
		 * ***********************************************************************************
		 * 获取天气信息异步任务
		 * @author csKevin
		 * ***********************************************************************************
		 */
		class WeatherTask extends AsyncTask<Void, Void, String>{
			
	            @Override
	            protected String doInBackground(Void... params) {
	            	manager = new NetAtmosphereManager();
	    			return manager.getWeatherDara(WeatherBean.WEATHER_URL1 + "101040100" + ".html");
	            }

	            @Override
	            protected void onPostExecute(String result) {
	                super.onPostExecute(result);
	                //Notify PullToRefreshAttacher that the refresh has finished
	                mPullToRefreshAttacher.setRefreshComplete();
	                if(result != null){
	                	wb = manager.parseWeatherBean(result);
	                	setGraphData();
	                	myApplication.setvHome(content);
	                }else{
	                	
	                }
	            }
			}
}
